
//
//  AccountViewModel.swift
//  SinaWeiBo
//
//  Created by 有风 on 16/2/18.
//  Copyright © 2016年 YouFeng. All rights reserved.
//

import UIKit
import AFNetworking

class AccountViewModel: NSObject {

    
    static let sharedAccountViewModel:AccountViewModel = AccountViewModel()
    //定义用户账户模型属性
    var userAccount: UserAccount?
    private override init() {
        super.init()
        userAccount = UserAccount.loadUserAccount()
    }
    
    //用户是否登录
    var userLogin: Bool {
        return userAccount?.access_token != nil
    }
    
    //当前登录的用户的token
    var access_token: String? {
        return userAccount?.access_token
    }
    //用户名
    var userName: String? {
        return userAccount?.name
    }
    
    //用户头像url
    var headImageUrl: NSURL? {
        if let urlString: String = userAccount?.avatar_large {
            return NSURL(string: urlString)
        }
        return nil
    }
    
    
    //加载用户的token
    func loadAccessToken(code:  String,finished: (isSuccess: Bool) -> ()) {
        // 使用AFN发起post的http请求
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //以字典的格式传递参数
        let parameters = ["client_id":client_id,"client_secret": client_secret ,"grant_type":"authorization_code","code":code, "redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            //将AnyObject类型的数据转换为字典数据
            // as? 尝试将Anyobject 转换为 字典类型数据
            guard let dict = result as? [String : AnyObject] else {
                //数据类型不匹配 默认访问出错
                finished(isSuccess: false)
                return
            }
            //程序走到这里 就一定转换为了字典类型数据
            let userAccount = UserAccount(dict: dict)
            print(userAccount)
            
            //获取用户信息 发起网络请求
            self.loadUserInfo(userAccount, finished: finished)
            
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }
    }
    
    
    //MARK: 请求用户信息
    private func loadUserInfo(userAccount: UserAccount,finished: (isSuccess: Bool) -> ()) {
        //获取用户信息的接口 返回的数据 是AFN默认支持解析的格式 并不是每一个都需要设置解析格式
        let urlString = "https://api.weibo.com/2/users/show.json"
        //OC中向字典中添加空对象 只能够添加 [NSNull null]
        //程序员保证一定能够获取到这些属性对应的值
        let parameters = ["access_token": userAccount.access_token!, "uid": userAccount.uid!]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            //将AnyObject类型的数据转换为字典数据
            // as? 尝试将Anyobject 转换为 字典类型数据
            guard let dict = result as? [String : AnyObject] else {
                finished(isSuccess: false)
                return
            }
            
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            //完善模型数据
            userAccount.name = name
            userAccount.avatar_large = avatar_large
            //            print(userAccount)
            
            //使用完整的对象 调用归档的方法
            userAccount.saveAccount()
            
            
            
            ///
            self.userAccount = userAccount
            //用户信息保存完毕之后 执行成功的回调
            finished(isSuccess: true)
            }) { (_, error) -> Void in
                //执行失败的回调
                finished(isSuccess: false)
                print(error)
        }
    }

}
